package 题集.力扣.算法精选200.字符串压缩;

/**
 * https://leetcode.cn/problems/compress-string-lcci/
 */
class Solution {
    public String compressString(String S) {
        if(S.length() == 0) {
            return S;
        }

        char[] chars = S.toCharArray();
        // 压缩后的字符串
        StringBuilder sb = new StringBuilder();

        // 快慢指针
        int slow = 0, fast = 0;

        while(fast <= chars.length){
            if(fast == chars.length){
                sb.append(chars[slow]).append(fast-slow);
            }else if(chars[fast] != chars[slow]){
                sb.append(chars[slow]).append(fast-slow);
                slow = fast;
            }
            fast++;
        }

        return sb.length() < chars.length ? sb.toString() : S;
    }

    public static void main(String[] args) {
        System.out.println(new Solution().compressString("aabcccccaaa"));
    }
}